//
//  NCFilterTabButton.swift
//  FilterBox
//
//  Created by 张文晏 on 2018/11/7.
//  Copyright © 2018 张文晏. All rights reserved.
//

import UIKit
import SnapKit

public class NCFilterTabButton: UIView {
    
    public let button = UIButton(type: .custom)
    
    @objc public func clickAction() {
        if let idx = filterBox.singleItems.index(where: { $0.tabButton.isSelected }) {
            let item = filterBox.singleItems[idx]
            item.filterTable.hide()
            item.tabButton.isSelected = false
            return
        }
        button.isSelected = true
        table?.show()
    }
    
    public var filterBox : NCFilterBox!
    public var table: NCFilterTable?
    public var originalTitle = ""
    public var isSelected : Bool{
        set {
            button.isSelected = newValue
        }
        get {
            return button.isSelected
        }
    }
    
    convenience public init(name: String) {
        self.init(frame: CGRect.init(x: 0, y: 0, width: 50, height: 44))
        button.setTitle(name, for: .normal)
        originalTitle = name
        setImage()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(button)
        button.snp.makeConstraints { $0.edges.equalToSuperview() }
        button.semanticContentAttribute = UISemanticContentAttribute.forceRightToLeft
        button.titleLabel?.font = .systemFont(ofSize: 14)
        button.setTitleColor(UIColor(hex: 0x333333), for: .normal)
        button.setTitleColor(UIColor(hex: 0x006fff), for: .selected)
        button.addTarget(self, action: #selector(clickAction), for: .touchUpInside)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func set(name: String, selected: Bool) {
        button.setTitle(name, for: .normal)
        if selected {
            button.setTitleColor(UIColor.init(hex: 0x006fff), for: .normal)
            button.setImage(NCUIBundle.image("ui_filter_triangle_down_blue"), for: .normal)
        } else {
            button.setTitleColor(UIColor.init(hex: 0x333333), for: .normal)
            button.setImage(NCUIBundle.image("ui_filter_triangle_down_gray"), for: .normal)
        }
    }
    
    func setImage() {
        button.setImage(NCUIBundle.image("ui_filter_triangle_down_gray"), for: .normal)
        button.setImage(NCUIBundle.image("ui_filter_triangle_up_blue"), for: .selected)
    }
    
}
